import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入Login组件
import Login from '../components/Login'
// 导入Home组件
import Home from '../components/Home'
// 导入Welcome组件
import Welcome from '../components/Welcome'
// 导入Users组件
import Users from '../components/user/Users'
// 导入Rights组件
import Rights from '../components/power/Rights'
// 导入Roles组件
import Roles from '../components/power/Roles'
// 导入Cate组件
import Cate from '../components/goods/Cate'
// 导入Params组件
import Params from '../components/goods/Params'
// 导入List组件
import List from '../components/goods/List'
// 导入Add组件
import Add from '../components/goods/Add'

// 导入Order组件
import Order from '../components/order/Order'

// 导入Report组件
import Report from '../components/report/Report'

Vue.use(VueRouter)

const routes = [
  // 重定向路由规则
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: List },
      { path: '/goods/add', component: Add },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

const router = new VueRouter({
  routes
})

//  挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //  to代表将要访问的路径
  //  from代表从哪个路径来
  //  next是一个函数（有三种方式放行：next（）  next（‘/路径’）  ）

  //  判断用户跳转的是不是登录页
  if (to.path === '/login') {
    //  是登录页
    return next()
  } else {
    // 不是登录页
    //  获取token
    const tokenStr = window.sessionStorage.getItem('token')
    //  判断token是否为空
    if (!tokenStr) {
      // 为空
      return next('/login')
    } else {
      //  不为空
      next()
    }
  }
})

export default router
